<template>
  <view class="goods-detail">
    <view class="content">
      <u-swiper
        :list="data.image_urls"
        indicator
        indicatorMode="line"
        circular
        height="400"
      ></u-swiper>
      <view class="info">
        <view class="card">
          <view v-if="isShowActivity" class="mb-10 flex gap-20 items-center">
            <view class="price">
              <text style="font-size: 26rpx">￥</text>
              <text>
                {{ data.sale_price ? formatActivityPrice : "***" }}
              </text>
              <text class="text-info" style="font-size: 28rpx">
                /{{ data.uom?.name }}</text
              >
            </view>
            <view class="price no">
              <text style="font-size: 26rpx">￥</text>
              <text>{{ defaultVariant.sale_price }}</text>
              <text class="text-info" style="font-size: 28rpx">
                /{{ data.uom?.name }}</text
              >
            </view>
          </view>
          <view v-else class="mb-10 flex gap-20 items-center">
            <view class="price">
              <text style="font-size: 26rpx">￥</text>
              <text>
                {{ data.sale_price ? defaultVariant.sale_price : "***" }}
              </text>
              <text class="text-info" style="font-size: 28rpx">
                /{{ data.uom?.name }}</text
              >
            </view>
            <view class="price no">
              <text style="font-size: 26rpx">￥</text>
              <text>{{ defaultVariant.guiding_price }}</text>
              <text class="text-info" style="font-size: 28rpx">
                /{{ data.uom?.name }}</text
              >
            </view>
          </view>
          <view class="mb-10">
            <u-text :lines="2" size="16" bold :text="data.name"></u-text>
          </view>
          <view v-if="data.barcode" class="field">
            <view class="label">商品条码</view>
            <view class="value">{{ data.barcode }}</view>
          </view>
        </view>
        <view class="card" style="margin-top: 20rpx">
          <view class="field">
            <view class="label">配送</view>
            <view class="value">
              <view style="font-size: 28rpx; color: #000; font-weight: bold">
                {{ data.supplier.name }}
              </view>
              <view>
                同城当日17:00之前下单，次日送达。当日17:00之后下单，隔日送达。
              </view>
            </view>
          </view>
        </view>
        <view class="card" style="margin-top: 20rpx">
          <view class="mb-10">
            <u-text text="商品信息" size="16"></u-text>
          </view>
          <view class="field mb-10">
            <view class="label">商品名称</view>
            <view class="value">
              {{ data.name }}
            </view>
          </view>
          <view class="field mb-10" v-if="data.barcode">
            <view class="label">商品条码</view>
            <view class="value">
              {{ data.barcode }}
            </view>
          </view>
          <view class="field mb-10">
            <view class="label">规格</view>
            <view class="value"
              >1*{{ data.specification || 1 }}{{ data.uom?.name }}</view
            >
          </view>
          <view class="field mb-10" v-if="data.brand">
            <view class="label">商品品牌</view>
            <view class="value">{{ data.brand?.name }}</view>
          </view>
          <view class="field mb-10">
            <view class="label">生产日期</view>
            <view class="value">
              {{ data.created_at }}
            </view>
          </view>
          <view class="field mb-10">
            <view class="label">库存</view>
            <view class="value">{{ data.stock }}{{ data.uom.name }}</view>
          </view>
        </view>
        <view v-if="isShowDescription" class="card mt-20">
          <view class="mb-10">
            <u-text text="商品描述" size="16"></u-text>
          </view>
          <u-parse :content="data.description"></u-parse>
        </view>
        <view
          v-if="data.detail_images && data.detail_images.length > 0"
          class="card mt-20"
        >
          <view class="mb-10">
            <u-text text="商品描述" size="16"></u-text>
          </view>
          <view
            class="detail-images"
            v-for="(img, inx) in data.detail_images"
            :key="inx"
          >
            <image
              v-if="img"
              class="detail-img"
              :src="img"
              mode="widthFix"
            ></image>
          </view>
        </view>
      </view>
      <my-variants
        v-model:show="variantShow"
        :type="variantType"
        :productId="id"
        :activitySkus="activityData.skus"
      ></my-variants>
    </view>
    <view class="actions-bar">
      <view class="btns">
        <view class="btn" @click="toHome">
          <uni-icons type="home" size="24"></uni-icons>
          <u-text text="首页" align="center" size="14"></u-text>
        </view>
        <view class="btn" @click="toCart">
          <uni-icons type="cart" size="24"></uni-icons>
          <u-text text="购物车" align="center" size="14"></u-text>
          <view class="dot" v-if="productInCartCount">{{
            productInCartCount
          }}</view>
        </view>
        <view class="btn" @click="handleSwitchCollect">
          <uni-icons
            :type="isCollect ? 'heart-filled' : 'heart'"
            size="24"
            :color="isCollect ? '#E74E5D' : ''"
          ></uni-icons>
          <u-text
            :text="isCollect ? '已收藏' : '收藏'"
            align="center"
            size="14"
          ></u-text>
        </view>
      </view>
      <!-- <view class="add" @click="handleAddCart">加入购物车</view> -->
      <view class="flex items-center" style="gap: 10rpx">
        <!-- <view v-if="isCart(id)">
          <up-number-box
            v-model="checkCart[data.id].num"
            :min="0"
            :max="data.stock"
            integer
            disabledInput
            @change="handleCartCountChange"
          ></up-number-box>
        </view> -->
        <u-button type="primary" @click="handleAddCart"> 加入购物车</u-button>
        <u-button
          :customStyle="{ marginLeft: '10rpx' }"
          type="warning"
          @click="handleAddStore"
        >
          加入云店
        </u-button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { computed, reactive, ref, watch } from "vue";
import {
  goodsDetail,
  addStore,
  promotionalGoodsDetail,
} from "@/common/apis/goods.js";
import { onShareAppMessage, onShow } from "@dcloudio/uni-app";
import { useStore } from "vuex";

const store = useStore();

const props = defineProps({
  id: String,
  activityProductId: String,
});

const variantShow = ref(false);

const variantType = ref("cart");

const data = reactive({
  barcode: "",
  brand: { id: 0, name: "", image_url: null },
  category: { id: 0, name: "", parent_id: 0, image_url: "" },
  created_at: "",
  description: "",
  express_amount: "",
  guiding_price: null,
  id: 0,
  image_url: "",
  image_urls: [],
  is_active: true,
  merchant: null,
  min_sale_quantity: 0,
  name: "",
  origin: "",
  origin_product: null,
  sale_number: 0,
  sale_price: null,
  specification: "",
  stand_price: null,
  stock: 0,
  supplier: { id: 0, name: "" },
  uom: { id: 0, group: { id: 0, name: "" }, name: "" },
  updated_at: "",
  skus: [],
});

const activityData = reactive({
  skus: [],
});

const isSingleSku = computed(() => {
  return data.skus.length && data.skus.length == 1;
});

const defaultVariant = computed(() => {
  return data.skus[0] ? data.skus[0] : {};
});

const cartCount = computed(() => {
  return store.getters.getInCartCount(props.id);
});

// 是否已收藏
const isCollect = computed(() => {
  return store.state.goods.collectList.some((i) => i.product.id == props.id);
});

const checkCart = computed(() => {
  return store.state.cart.checkCart;
});

const isShowActivity = computed(() => {
  return props.activityProductId;
});

const isShowDescription = computed(() => {
  if (
    /<([a-zA-Z][a-zA-Z0-9-]*)(?:\s+[^>]*)?>\s*<\/\1>/.test(data.description)
  ) {
    return true;
  }
  return false;
});

const productInCartCount = computed(() => {
  let count = 0;
  const productCartList = store.state.cart.list.filter(
    (i) => i.product.id == props.id
  );
  productCartList.forEach((item) => {
    count += item.quantity;
  });
  console.log(count);
  return count;
});

const formatActivityPrice = computed(() => {
  return activityData.skus[0] ? activityData.skus[0].amount : "";
});

// 检测是否为购物车商品
function isCart(id) {
  return Object.keys(checkCart.value).includes(id + "");
}

// 获取商品详情信息
async function fetchGoodsDetail() {
  const response = await goodsDetail(props.id);
  if (response) {
    Object.assign(data, response);
  }
  if (props.activityProductId) {
    const response = await promotionalGoodsDetail(props.activityProductId);
    if (response) {
      Object.assign(activityData, response);
    }
  }
}

function toHome() {
  uni.reLaunch({
    url: "/pages/index/index",
  });
}

function toCart() {
  uni.reLaunch({
    url: "/pages/index/cart",
  });
}

function getCurrentCartId() {
  return store.state.cart.list.find((i) => i.product.id == props.id).id;
}

function handleCartCountChange(e) {
  if (e.value == 0) {
    store.dispatch("fetchDelCart", getCurrentCartId());
    return;
  }
  if (e.value > cartCount.value) {
    store.dispatch("fetchAddCart", {
      product_id: Number(props.id),
      quantity: "+1",
    });
    return;
  }
  if (e.value < cartCount.value) {
    store.dispatch("fetchAddCart", {
      product_id: Number(props.id),
      quantity: "-1",
    });
    return;
  }
}

async function handleSwitchCollect() {
  if (isCollect.value) {
    await store.dispatch("fetchDelCollect", props.id);
  } else {
    await store.dispatch("fetchAddCollect", props.id);
  }
  await store.dispatch("fetchCollectList");
}

async function handleAddCart() {
  if (data.skus.length > 1) {
    variantType.value = "cart";
    return (variantShow.value = true);
  } else {
    // 默认变体
    const sku = data.skus[0];
    if (sku.stock > data.min_sale_quantity) {
      const currentCartSku = store.state.cart.list.find(
        (i) => i.variant.id == sku.id
      );
      await store.dispatch("fetchAddCart", {
        product_id: props.id,
        variant_id: sku.id,
        quantity: currentCartSku ? 1 : data.min_sale_quantity,
        promotional_variant_id: isShowActivity.value
          ? activityData.skus[0].id
          : undefined,
      });
      await store.dispatch("fetchCartList");
    } else {
      uni.$u.toast("库存不足");
    }
  }
}

async function handleAddStore() {
  variantType.value = "selection";
  variantShow.value = true;
  // const response = await addStore(props.id);
  // if (response) {
  //   uni.$u.toast("成功加入云店");
  // }
}

onShow(async () => {
  // #ifdef MP-WEIXIN
  uni.showShareMenu({
    withShareTicket: true,
    menus: ["shareAppMessage"],
  });
  // #endif
  await fetchGoodsDetail({ id: props.id });
});

onShareAppMessage(() => {
  return {
    title: data.name,
    path: `/pages/goods/detail?id=${props.id}`,
  };
});
</script>

<style lang="scss" scoped>
.goods-detail {
  height: 100%;
  display: flex;
  flex-direction: column;

  .content {
    flex: 1;
    overflow-y: auto;
    background-color: #f0f0f0;

    .info {
      padding: 20rpx;
    }

    .card {
      border-radius: 10rpx;
      padding: 20rpx;
      background-color: #fff;

      .price {
        font-size: 18px;
        color: #ff2122;

        &.no {
          color: $u-info-disabled;
          text-decoration: line-through;
          font-size: 16px;
        }
      }

      .field {
        display: flex;

        .label {
          font-size: 14px;
          width: 140rpx;
          color: $u-info;
        }

        .value {
          font-size: 14px;
          flex: 1;
        }
      }
    }
  }

  .detail-img {
    width: 100%;
    display: block;
  }

  .actions-bar {
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 20rpx calc(20rpx + env(safe-area-inset-bottom));

    .btns {
      display: flex;

      .btn {
        width: 100rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        position: relative;

        .dot {
          min-width: 30rpx;
          position: absolute;
          top: -20rpx;
          right: -10rpx;
          background-color: #f56c6c;
          border-radius: 30rpx;
          padding: 5rpx 10rpx;
          color: #fff;
          text-align: center;
        }
      }
    }

    .add {
      background-color: $u-primary;
      color: #fff;
      padding: 20rpx 40rpx;
      border-radius: 10rpx;
    }
  }
}
</style>
